﻿using NHibernate;
using NHibernate.Criterion;
using ProjectDAL.Entities;
using ProjectDAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectDAL
{
    public class ProjectDAL : IProjectDAL
    {
        private ISession Session;

        public ProjectDAL(ISession Session)
        {
            this.Session = Session;
        }
        public int AddUser(User user)
        {
            Session.Save(user);
            return user.Id;
        }

        public User GetUser(UserSearchCriteria userSearchCriteria)
        {
            var criteria = Session.CreateCriteria(typeof(User));
            if (userSearchCriteria != null)
            {
                User user = null;
                if (userSearchCriteria.Id != 0)
                {
                    user = criteria.List<User>().Where(x => x.Id.Equals(userSearchCriteria.Id)).FirstOrDefault();
                }
                else
                {
                    // Search user
                    user = criteria.List<User>().Where(x => x.UserName.Equals(userSearchCriteria.UserName) && x.Password.Equals(userSearchCriteria.Password)).FirstOrDefault();
                }
                return user;    
            }
            return null;
           
        }

        public Project GetProjectById(ProjectPk projectPk)
        {
            return Session.Get<Project>(projectPk.Id);
        }

        public int AddProject(Project project)
        {
            var objUser = this.GetUser(new UserSearchCriteria
            {
                Id = project.User.Id
            });
            project.User = objUser;
            Session.Save(project);
            return project.Id;
        }
    }
}
